#!/usr/bin/env python
'''
The first time checks
'''

import gtk
import Gui
import os
from Config import get_config
from pysqlite2 import dbapi2 as sqlite

class FirstTime:
    def __init__(self):
        if (not self.dbExists()):
            Gui.InfoBox(str="This is the first time you use " + get_config("title") +
                        ". I'm going to create a database for you...")
            self.createDB()
            self.checkDB()
            self.connection.close()

    def dbExists(self):
        '''Returns True if the database already exists, or
        False if it doesn't.'''
        return os.path.exists("coasters.db")

    def createDB(self):
        '''If the db doesn't exist, this function creates it'''
        f = file("db.sql")
        self.connection = sqlite.connect("coasters.db")
        self.cursor = self.connection.cursor()

        error = False
        for line in f:
            try:
                self.cursor.execute(line)
            except:
                error = True

        if (error):
            Gui.ErrorBox(str="Can't initialize the database!")
            sys.exit(1)
        self.connection.commit()

    def checkDB(self):
        '''Perform a test query to see if everything is in place'''
        try:
            self.cursor.execute("SELECT * FROM breweries")
            self.cursor.execute("SELECT * FROM brands")
            self.cursor.execute("SELECT * FROM coasters")
        except:
            Gui.ErrorBox(str="Can't initialize the database!")
            os.remove("coasters.db")
            sys.exit(1)

